package com.yh.controller;

import com.yh.javabean.ResultObject;
import com.yh.javabean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @Auther: Liang
 * @Date: 2024/5/17 - 05 - 17 - 10:17
 * @Description: com.yh.controller
 * @version: 1.0
 */
@Controller
public class MyController {
   @RequestMapping(value = "/a.do",method = RequestMethod.GET)
    public void a (){
        System.out.println("c+5");
    }

    //数据响应-页面跳转
    //1、方法返回字符串类型
     @RequestMapping("/b.do")
    public String b(){
       //重定向跳转页面
         return "/index.jsp";
    }

    //2、页面跳转-通过ModelAndView对象返回
    @RequestMapping("/c.do")
    public ModelAndView save2(){
        //  Model:模型 作用封装数据
        //  View：视图 作用展示数据
        //  将跳转的页面与传递的数据存入
        ModelAndView view = new ModelAndView();
         view.setViewName("/index.jsp");
        return view;
    }
    //springmvc数据响应-返回数据
    //1、通过response响应对象回写数据
    //通过spring可以为方法的参数列表进行自动注入
    @RequestMapping("/req3.do")
    public void req3(HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.println("data-response");
    }

    //2、将方法返回值设置为String直接return返回
    //直接返回的话需要使用@ResponseBody注解 用来告诉视图解析器该返回值 无需解析
    @RequestMapping("/req4.do")
    @ResponseBody
    public String req4(){
       return "data-string-@ResponseBody";
    }

    //3、返回对象或集合
    //通过该方法可以直接将返回的对象或集合，通过配置springmvc会自动使用jackson将其转换
    //为json格式的字符串并返回
    @RequestMapping("/req5.do")
    @ResponseBody
    public User req5(){
        User u=new User(1,"lisi",18);
        return u;
    }
    //返回集合
    @RequestMapping("/req6.do")
    @ResponseBody
    public ArrayList<User> req6(){
        User u1=new User(1,"lisi1",181);
        User u2=new User(2,"zahngsan",182);
        User u3=new User(3,"nihao",183);
        User u4=new User(4,"zhaoliu",184);
        ArrayList<User> list=new ArrayList<>();
        Collections.addAll(list,u1,u2,u3,u4);
        return list;
    }


    //回写数据通用语句返回
    @RequestMapping("/req7.do")
    @ResponseBody
    public ResultObject<User> req7(){
        User u1=new User(1,"lisi1",181);
        User u2=new User(2,"zahngsan",182);
        User u3=new User(3,"nihao",183);
        User u4=new User(4,"zhaoliu",184);
        ArrayList<User> list=new ArrayList<>();
        Collections.addAll(list,u1,u2,u3,u4);
        ResultObject<User> resultObject=new ResultObject<>(20,"123",list);
        return resultObject;
    }
}
